package db

import (
	"database-platform/dal"
	"database-platform/logger"
	"database-platform/model"
	"fmt"
	"time"
)

func ListServerRecords(server *model.Server, page, pageSize int64, search string) ([]*model.Server, uint64, error) {
	var query = dal.GORM
	var records []*model.Server
	var count uint64

	if server.Hostname != "" {
		query = query.Where("hostname = ?", server.Hostname)
	}
	if server.IP != "" {
		query = query.Where("ip = ?", server.IP)
	}
	if server.Env != "" {
		query = query.Where("env = ?", server.Env)
	}
	if server.DBType != "" {
		query = query.Where("db_type = ?", server.DBType)
	}

	if search != "" {
		query = query.Where("hostname like ?", "%"+search+"%").
			Or("ip like ?", "%"+search+"%")
	}

	if page > 0 && pageSize > 0 {
		offset := (page - 1) * pageSize
		query = query.Offset(offset).Limit(pageSize)
	}

	err := query.Find(&records).Count(&count).Error
	if err != nil {
		msg := fmt.Sprintf("【DB.LOG】 db.server.ListServerRecords sql execute err, err message is %s, server: %v", err, server)
		logger.Logger.Error(msg)
		return nil, 0, err
	}
	return records, count, nil
}

func GetServerRecordById(id int) (record *model.Server, err error) {
	record = &model.Server{}
	tx := dal.GORM.Where("id = ?", id).First(&record)
	if tx.Error != nil {
		msg := fmt.Sprintf("【DB.LOG】 db.server.GetServerRecordById.sql.execute.err.message.%s.id.%v", tx.Error, id)
		logger.Logger.Error(msg)
		return nil, tx.Error
	}

	return record, nil
}

// InsertServerRecord 插入服务器记录
func InsertServerRecord(server *model.Server) error {
	server.UpdateTime = time.Now()
	server.CreateTime = time.Now()
	err := dal.GORM.Create(server).Error
	if err != nil {
		msg := fmt.Sprintf("【DB.LOG】 db.server.InsertServerRecord sql execute err, err message is %s, server: %v", err, server)
		logger.Logger.Error(msg)
		return err
	}
	return nil
}

// UpdateServerRecord 更新服务器记录
func UpdateServerRecord(id int, server *model.Server) error {
	server.UpdateTime = time.Now()
	server.ID = int64(id)
	err := dal.GORM.Save(server).Error
	if err != nil {
		msg := fmt.Sprintf("【DB.LOG】 db.server.UpdateServerRecord sql execute err, err message is %s, server: %v", err, server)
		logger.Logger.Error(msg)
		return err
	}
	return nil
}

// DeleteServerRecord 删除服务器记录
func DeleteServerRecord(id int) error {
	err := dal.GORM.Delete(&model.Server{}, id).Error
	if err != nil {
		msg := fmt.Sprintf("【DB.LOG】 db.server.DeleteServerRecord sql execute err, err message is %s, id: %d", err, id)
		logger.Logger.Error(msg)
		return err
	}
	return nil
}
